package cn.fangline.wo.task.akka.actors;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import cn.fangline.wo.model.OriginHouse;
import cn.fangline.wo.task.akka.messages.Tick;
import scala.concurrent.duration.Duration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by 抽离 on 2017/6/26 0026.
 */
public class HousePackActor extends AbstractActor {

    private ActorRef houseExistRef;

    public HousePackActor(ActorRef houseExistRef) {
        this.houseExistRef = houseExistRef;
    }

    private List<OriginHouse> bag = new ArrayList<>();

    private Long latestPackTime = 0l;

    @Override
    public void preStart() {
        getContext().getSystem().scheduler().scheduleOnce(
                Duration.create(500, TimeUnit.MILLISECONDS),
                getSelf(),
                new Tick(1l),
                getContext().dispatcher(),
                null
        );
    }

    @Override
    public Receive createReceive() {
        return
                receiveBuilder()
                    .match(OriginHouse.class, this::onReceiveOriginHouse)
                     .match(Tick.class, m -> {
                            Long c = System.currentTimeMillis()/1000;
                            if(((latestPackTime+5)<c) && (bag.size()>0)){
                                houseExistRef.tell(bag,self());
                                bag = new ArrayList<>();
                                latestPackTime = c;
                            }
                            getContext().getSystem().scheduler().scheduleOnce(
                                    Duration.create(5, TimeUnit.SECONDS),
                                    getSelf(),
                                    new Tick(m.round+1),
                                    getContext().dispatcher(),
                                    null
                            );
                        })
                    .build();
    }

    private void onReceiveOriginHouse(OriginHouse originHouse) {
//        System.out.println("得到打包的houses：" + originHouse);
        bag.add(originHouse);
        if(bag.size()>=100){
            houseExistRef.tell(bag, getSelf() );
            bag = new ArrayList<>();
            latestPackTime = System.currentTimeMillis()/1000;
        }
    }
}
